package com.korion.srceencapture;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.media.Image;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * @author chenyinying
 * @date 2020/9/20
 */
public class BitmapHandler extends HandlerThread {

    static class InstanceHolder {
        static BitmapHandler instance = new BitmapHandler();
    }

    public static final String TAG = "BitmapHandler";

    private Context appContext;

    private Handler mHandler;

    private String mBase;

    private boolean mInit;

    public static BitmapHandler inst() {
        return InstanceHolder.instance;
    }

    public BitmapHandler() {
        this("Bitmap Handler");
    }

    public BitmapHandler(String name) {
        super(name);
    }

    @Override
    protected void onLooperPrepared() {
        mHandler = new Handler(getLooper());
    }

    public boolean isInit() {
        return mInit;
    }

    public boolean init(Context context){
        appContext = context.getApplicationContext();
        File dir = appContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (dir == null) {
            mInit = false;
            return false;
        }
        mBase = dir.getAbsolutePath();
        start();
        mInit = true;
        return true;
    }

    public void postSaveBitmap(final Bitmap bitmap, final String name){
        if (!isInit()) {
            return;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                saveBitmapToFile(bitmap, String.format("%s/%s", mBase, name));
            }
        });
    }

    public void postSaveImage(final Image image, final String name) {
        if (!isInit()) {
            return;
        }
        if (Thread.currentThread().equals(getLooper().getThread())){
            saveImageToFile(image, String.format("%s/%s", mBase, name));
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    saveImageToFile(image, String.format("%s/%s", mBase, name));
                }
            });
        }
    }

    public void release() {
        quitSafely();
    }

    public Handler getHandler(){
        return mHandler;
    }


    public static void saveBitmapToFile(Bitmap bitmap, String path){
        if (bitmap == null || bitmap.isRecycled()) {
            Log.e(TAG, "no valid bitmap");
            System.out.println("no valid bitmap");
            return;
        }
        File file = new File(path);
        if (file.exists() && !file.delete()) {
            Log.e(TAG, "delete exist file fail");
            System.out.println("delete exist file fail");
            return;
        }
        try (FileOutputStream out = new FileOutputStream(file)){
            if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){
                Log.e(TAG, "save bitmap to file fail,"+path);
                System.out.println("save bitmap to file fail,"+path);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }


    private static void saveImageToFile(Image image, String path){
//        Image.Plane[] planes = image.getPlanes();
//        ByteBuffer buffer = planes[0].getBuffer();
//        byte[] bytes = new byte[buffer.capacity()];
//        buffer.get(bytes);
//        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, option);
//        image.close();
        int width = image.getWidth();
        int height = image.getHeight();
        Log.d(TAG, "width:"+width+", height:"+height);
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        Log.d(TAG, "format: "+image.getFormat()+", planes:"+planes.length);
        Bitmap bitmap = null;
        if (image.getFormat() == ImageFormat.HEIC) {
            byte[] data = new byte[buffer.capacity()];
            buffer.get(data);
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        } else {
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
        }
        image.close();
        saveBitmapToFile(bitmap, path);
    }
}
